package com.pl.rabarbar.old.stuff.need.to.be;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.pl.rabarbar.convert.ConvertJson;
import com.pl.rabarbar.services.GetFromServer;

public class Deamon extends Observable implements ServletContextListener,
		Runnable {

	private Thread thread;
	private List idList;

	/**
	 * Observable part from
	 * http://www.javaworld.com/article/2077258/learn-java/observer
	 * -and-observable.html
	 * 
	 * @param list
	 */

	public void setValue(List list) {
	//	this.idList = list;
		if (this.idList == null)
			this.idList = new ArrayList<String>(list);
		else {
			idList.clear();
			idList.addAll(list);

		}
		setChanged();
		notifyObservers();
	}

	private void setList(List idList) {
		
	}

	public List getValue() {
		return this.idList;
	}

	/**
	 * Runnable part
	 */
	@Override
	public void run() {
		while (true) {

			try {
				this.setValue((List) ConvertJson.convertFromJsonToList(GetFromServer
						.getFromServer("http://localhost:8080/BookstoreTest/bookstore/getAllId")));

				TimeUnit.MINUTES.sleep(10);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			/*
			 * pobieranie danych co 10 minut
			 */
		}

	}

	public List getIdList() {
		return idList;
	}

	public Thread getThread() {
		return thread;
	}

	public void setThread(Thread thread) {
		this.thread = thread;
	}

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		this.thread.interrupt();

	}

	@Override
	public void contextInitialized(ServletContextEvent e) {
		ServletContext cntx = e.getServletContext();

		thread = new Thread(this);
		thread.start();
		ListObserver lo = new ListObserver();
		this.addObserver(lo);
		synchronized(cntx){
			cntx.setAttribute("ListObserver", lo);
			cntx.setAttribute("idList", this.idList);
		}
		
	}

}
